<template>
  <div>
    <div id="loadOverlay" class='loadingOverlay'>
            <ul id="loadbar" class="ins">
                <li>
                    <div id="loadinglayer1" class="ball"></div>
                    <div id="loadinglayer7" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer2" class="ball"></div>
                    <div id="loadinglayer8" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer3" class="ball"></div>
                    <div id="loadinglayer9" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer4" class="ball"></div>
                    <div id="loadinglayer10" class="pulse"></div>
                </li>
                <li>
                    <div id="loadinglayer5" class="ball"></div>
                    <div id="loadinglayer11" class="pulse"></div>
                </li>
            </ul>
        </div>
        <div id="mask" class="signmask"></div>


        <div id="centerDiv">
            <div id="redslibContainer" class="redslib-container" style="height:100%"></div>
        </div>

        <div class="test-btn">
            <button  @click="showWidgets()">显示widgets组件</button><br>
            <button  @click="drawEntityByJson()">调用标绘上图</button>
            <button  @click="deletePlotEntity()">删除标绘上图</button><br>
<!--            <button  @click="viewerEntityOnMap()">调用viewer上图</button>-->
<!--            <button  @click="deleteViewerEntity()">删除viewer上图</button>-->
        </div>

    <div class="tan"  v-show="yonghuB" style="overflow-y:auto">
      <div class="title_tan">
        <!-- <div style="width: 95%;float: left">用户信息</div> -->
        <div style="width: 5%;float: right;font-size: 16px;cursor: pointer;"
             @click="handleClose">X</div>
      </div>
      <div >
<!--        <el-select-->
<!--          v-show="listpd==1"-->
<!--          v-model="value"-->
<!--          filterable-->
<!--          placeholder="Select"-->
<!--          style="width: 100%"-->
<!--          @change="showYongHu"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="item in yonghu"-->
<!--            :key="item.id"-->
<!--            :label="item.label"-->
<!--            :value="item.id"-->
<!--          />-->
<!--        </el-select>-->
        <div style="font-size: 16px;">
          人口数量：{{yonghuList.length}}
        </div>
        <div v-if="listpd==2">
          <div v-for="item in yonghuList" style="padding: 10px;font-size: 16px;line-height: 24px;color:white;    background: rgba(17, 42, 58, 0.5);
    border-radius: 6px;
    box-shadow: 0 0 10px rgba(17, 42, 58, 0.5);margin-top: 8px;">
            <div>姓名: {{item.realName}}</div>
            <div v-show="item.sex==0">性别：男</div>
            <div v-show="item.sex==1">性别：女</div>
            <div>与户主关系：{{item.relationship}}</div>
            <div>电话：{{item.mobile}}</div>
        </div>
<!--        <div style="padding: 10px;font-size: 16px;line-height: 24px;color:white;    background: rgba(17, 42, 58, 0.5);-->
<!--    border-radius: 6px;-->
<!--    box-shadow: 0 0 10px rgba(17, 42, 58, 0.5);margin-top: 8px;">-->
<!--            <div>姓名: 刘根娣</div>-->
<!--            <div>性别：女</div>-->
<!--            <div>与户主关系：夫妻</div>-->
<!--            <div>身份职务：无</div>-->
<!--        </div>-->
        </div>
<!--        <div v-if="listpd==1">-->
<!--          <el-button  type="primary" @click="baocun">保存</el-button>-->
<!--        </div>-->
      </div>
    </div>
  </div>

</template>

<script>
import baseService from "@/service/baseService";
import {ElNotification} from "element-plus";

export default {
  name: 'R3DMap',
  props: {
  },
  data() {
    return {
      title: 'R3D地图',
      drawControl: null,
      dialogVisible:true,
      yonghu:[
        {
          id:"1067246875800000064",
          label:"塍里"
        },
        {
          id:"1733419574956113921",
          label:"2-102"
        },



      ],
      yonghuList:[],
      value:"请选择",
      yonghuB:false,
      baocunyonghu:"",
      json1:{},
      listpd:0,
      biaozhulist:[]
    };
  },
  mounted() {
      this.initMap();

  },
  methods: {
    startDrawPoint() {
      let pointDefval = {
        "edittype": "point",
        "name": "点标记",
        "style": {
          "pixelSize": 10,
          "color": "#3388ff",
          "opacity": 1,
          "outline": true,
          "outlineColor": "#ffffff",
          "outlineOpacity": 0.6,
          "outlineWidth": 2,
        },
        "attr": {
          "id": "111",
          "name": "点标记"
        },
        "type": "point"
      }
      this.drawControl.startDraw(pointDefval);
    },
    baocun(){
      let that = this

      let pointId =that.json1.features[that.json1.features.length-1].properties.attr.id
      if( document.getElementsByClassName('redslib-viewer')[0]){
        baseService.post("/clc/clcmapnodeinfo",
          {jsonInfo: JSON.stringify(that.json1.features[that.json1.features.length-1]),pointId:pointId,deptId:that.baocunyonghu})
          .then((results) => {
            //debugger
            var strjson = results;
            var isClearForOpenFile = false; //是否清除已上图的entity
            var isFly = true; //上图后是否飞行到entity

            that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
          });
      }else {
        baseService.post("/clc/clcmapnodeinfo",
          {jsonInfo: JSON.stringify(that.json1.features[that.json1.features.length-1]),pointId:pointId,deptId:that.baocunyonghu})
          .then((results) => {
            //debugger

            var strjson = results;
            var isClearForOpenFile = false; //是否清除已上图的entity
            var isFly = true; //上图后是否飞行到entity

            that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
          });
      }
        this.yonghuB=false
    },
    //校验权限
    handleClose() {
        this.yonghuB=false
    },
    initDrawControl(viewer) {
      this.drawControl = new reds3d.Draw({
        viewer: viewer,
       // hasEdit: true,
        tooltip: true
      });
    },
     initMap() {
       let that = this;
       var request = haoutil.system.getRequest();
       var configfile = "/chenglicun/r3dUtil/config/config.json";
       // var configfile = "http://localhost:8019/data/mapConfig.json";
       if (request.config)
         configfile = request.config;
       haoutil.loading.show();
       if( document.getElementsByClassName('redslib-viewer')[0]){
         document.getElementsByClassName('redslib-viewer')[0].remove()
         reds3d.createMap({
           id: 'redslibContainer',
           // url: configfile + "?time=20231104",
           url: configfile,
           success: function (_viewer, gisdata, jsondata) {//地图成功加载完成后执行


             haoutil.loading.hide();
             window.viewer = _viewer;
             //初始化widget管理器
             var hasAnimation = true;
             if (haoutil.isutil.isNotNull(request.widget)) {
               jsondata.widget.widgetsAtStart = [];
               hasAnimation = false;
             }
             reds3d.widget.init(_viewer, jsondata.widget);
             that.initDrawControl(_viewer);

             baseService.get("/clc/clcmapnodeinfo/getInfo")
               .then((results) => {
                 var strjson = results.data;
                 var isClearForOpenFile = true; //是否清除已上图的entity
                 var isFly = true; //上图后是否飞行到entity
                 that.biaozhulist=results.data
                 that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
               });

             // $.ajax({
             //   type: "get",
             //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo/getInfo",
             //   async: false,
             //   success: function (results) {
             //     var strjson = results.data;
             //     var isClearForOpenFile = true; //是否清除已上图的entity
             //     var isFly = true; //上图后是否飞行到entity
             //
             //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
             //   }
             // });
             // 接受消息
             window.addEventListener('message', e => {
               if (e.data.type !== 'draw') return;
               if(e.data.widgets == 'plot-api'){ //接收标绘组件发送的消息
                 //debugger
                 console.log('标绘json:', e.data.data);
                 that.json1= e.data.data
                  that.yonghuB=true
                  that.listpd=1

                 // $.ajax({
                 //   type: "post",
                 //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo",
                 //   async: false,
                 //   contentType: "application/json",
                 //   data:JSON.stringify({jsonInfo: JSON.stringify(e.data.data.features[e.data.data.features.length-1])}),
                 //   success: function (results) {
                 //     //debugger
                 //     var strjson = results;
                 //     var isClearForOpenFile = false; //是否清除已上图的entity
                 //     var isFly = true; //上图后是否飞行到entity
                 //
                 //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
                 //
                 //   }
                 // });
                 const data = e.data.data;
                 if (!data) return;

                 //测试：保存到本地
                 //   saveJSON(data, 'data.json')
               }
             })
             setTimeout(function () {
               $("#mask").remove();
             }, 3000);
             that.loaderOK();

             window.viewer.screenSpaceEventHandler.setInputAction(async (move) => {
        const pickedObj = window.viewer.scene.pick(move.position)
        console.log(pickedObj)
      }, Redslib.ScreenSpaceEventType.RIGHT_CLICK)

             //如果有xyz传参，进行定位
             if (haoutil.isutil.isNotNull(request.x) && haoutil.isutil.isNotNull(request.y)) {
               window.viewer.wing.centerAt(request, { duration: 0, isWgs84: true });
             }

             function calback() {
               //如果url传参，激活对应widget
               if (haoutil.isutil.isNotNull(request.widget))
                 reds3d.widget.activate(request.widget);
               that.initWork(_viewer);
             }

             if (hasAnimation) //开场动画
               window.viewer.wing.openFlyAnimation(calback); //动画播放完成后执行calback回调
             else {
               calback();
             }
           }
         });
       }else {
         reds3d.createMap({
           id: 'redslibContainer',
           // url: configfile + "?time=20231104",
           url: configfile,
           success: function (_viewer, gisdata, jsondata) {//地图成功加载完成后执行


             haoutil.loading.hide();
             window.viewer = _viewer;
             //初始化widget管理器
             var hasAnimation = true;
             if (haoutil.isutil.isNotNull(request.widget)) {
               jsondata.widget.widgetsAtStart = [];
               hasAnimation = false;
             }
             reds3d.widget.init(_viewer, jsondata.widget);
             that.initDrawControl(_viewer);


             baseService.get("/clc/clcmapnodeinfo/getInfo")
               .then((results) => {
                  debugger
                 var strjson = results.data;
                 var isClearForOpenFile = true; //是否清除已上图的entity
                 var isFly = true; //上图后是否飞行到entity
                 that.biaozhulist=results.data
                 that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
               });

             // $.ajax({
             //   type: "get",
             //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo/getInfo",
             //   async: false,
             //   success: function (results) {
             //     var strjson = results.data;
             //     var isClearForOpenFile = true; //是否清除已上图的entity
             //     var isFly = true; //上图后是否飞行到entity
             //
             //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
             //   }
             // });
             // 接受消息
             window.addEventListener('message', e => {

               if (e.data.type !== 'draw') return;
               if(e.data.widgets == 'plot-api'){ //接收标绘组件发送的消息
                 //debugger
                 console.log('标绘json:', e.data.data);
                 that.json1= e.data.data
                 that.yonghuB=true
                 that.listpd=1

                 // $.ajax({
                 //   type: "post",
                 //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo",
                 //   async: false,
                 //   contentType: "application/json",
                 //   data:JSON.stringify({jsonInfo: JSON.stringify(e.data.data.features[e.data.data.features.length-1])}),
                 //   success: function (results) {
                 //     //debugger
                 //     var strjson = results;
                 //     var isClearForOpenFile = false; //是否清除已上图的entity
                 //     var isFly = true; //上图后是否飞行到entity
                 //
                 //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
                 //
                 //   }
                 // });
                 const data = e.data.data;
                 if (!data) return;

                 //测试：保存到本地
                 //   saveJSON(data, 'data.json')
               }
             })
             setTimeout(function () {
               $("#mask").remove();
             }, 3000);
             that.loaderOK();

             // 进入
             window.viewer.screenSpaceEventHandler.setInputAction(async (move) => {
        const pickedObj = window.viewer.scene.pick(move.position)
        console.log(pickedObj)
            const a =   pickedObj.id._attribute.attr.id
            debugger
               baseService.get(`/clcLocationMark/clclocationmark/getByMarkId/`+a).then((res) => {
                  debugger
                 that.yonghuList=res.data.personInfoList
                 var entityArr = that.drawControl.getEntitys();
                 for (let i = 0; i < entityArr.length; i++) {
                   console.log('entityArr:', entityArr[i]);
                   entityArr[i].popup = {
                     html: `<div style="width: 224px; height: 50px;"><p style="color: #ff0000;">111</p></div>`,
                     anchor: [0, -60]
                   };
                   // entityArr[i].tooltip = {
                   //               html: `<div style='min-width: 200px;text-align: center'>tooltip111</div>`
                   //           };

                 }
               });
               //
               // that.chaYongHu(a)
               that.yonghuB=true
               that.listpd=2
      }, Redslib.ScreenSpaceEventType.LEFT_CLICK)
            //MOUSE_OVER
             //如果有xyz传参，进行定位
             if (haoutil.isutil.isNotNull(request.x) && haoutil.isutil.isNotNull(request.y)) {
               window.viewer.wing.centerAt(request, { duration: 0, isWgs84: true });
             }

             function calback() {
               //如果url传参，激活对应widget
               if (haoutil.isutil.isNotNull(request.widget)) {
                reds3d.widget.activate(request.widget);
               }
                that.initWork(_viewer);
             }

             if (hasAnimation) //开场动画
               window.viewer.wing.openFlyAnimation(calback); //动画播放完成后执行calback回调
             else {
               calback();
             }
           }
         });
       }




     },
     loaderOK() {
        $("#loadOverlay").hide();
        $('#loadbar').removeClass('ins');
        Window.LOADING_FLAG = true;
     },
    initWork(viewer) {
      haoutil.oneMsg('如果未出现地球，是因为地形加载失败，请刷新重新加载！', 'terrain_tip');
      // 禁用默认的实体双击动作。
      viewer.screenSpaceEventHandler.removeInputAction(Redslib.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
       viewer.screenSpaceEventHandler.removeInputAction(Redslib.ScreenSpaceEventType.LEFT_CLICK);

      //移动设备上禁掉以下几个选项，可以相对更加流畅
      if (!haoutil.system.isPCBroswer) {
        viewer.targetFrameRate = 20; //限制帧率
        viewer.requestRenderMode = true; //取消实时渲染
        viewer.scene.fog.enable = false;
        viewer.scene.skyAtmosphere.show = false;
        viewer.scene.fxaa = false;
      }

      //IE浏览器优化
      if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
        viewer.targetFrameRate = 20; //限制帧率
        viewer.requestRenderMode = true; //取消实时渲染
      }

      //更改配置，性能优化
      viewer.scene.logarithmicDepthBuffer = false;


      //设置操作习惯,更换中键和右键
      viewer.scene.screenSpaceCameraController.tiltEventTypes = [
        Redslib.CameraEventType.RIGHT_DRAG, Redslib.CameraEventType.PINCH,
        { eventType: Redslib.CameraEventType.LEFT_DRAG, modifier: Redslib.KeyboardEventModifier.CTRL },
        { eventType: Redslib.CameraEventType.RIGHT_DRAG, modifier: Redslib.KeyboardEventModifier.CTRL }
      ];
      // MOUSE_MOVE
      viewer.scene.screenSpaceCameraController.zoomEventTypes = [Redslib.CameraEventType.MIDDLE_DRAG, Redslib.CameraEventType.WHEEL, Redslib.CameraEventType.PINCH];
    },

     showWidgets() {
        reds3d.widget.activate({
            uri: "/chenglicun/r3dUtil/map/widgets/toolBarRight/widget.js", //右上角工具栏组件
            data: [
                {
                    "name": "图层",
                    "icon": "fa fa-tasks",
                    "widget": "/chenglicun/r3dUtil/map/widgets/manageLayers/widget.js",
                    "visible": true
                },
                {
                    "name": "标绘",
                    "icon": "fa fa-object-group",
                    "widget": "/chenglicun/r3dUtil/map/widgets/plot-api/widget.js",
                    "visible": true
                }
            ]
        });
     },
     showYongHu(value){
      const deptId = {
          deptId:value
        }

       this.baocunyonghu=value
       baseService.get("/sys/user/page",deptId)
         .then((results) => {

          this.yonghuList =results.data

         });
     },
      chaYongHu(value){
      let  deptId = {
        deptId:""
      }
      let pointId ={
        pointId:value
      }

      baseService.get("/clc/clcmapnodeinfo/getInfoByPointId",pointId)
        .then((results) => {

          deptId = {
            deptId:results.data.deptId
          }
          baseService.get("/sys/user/page",deptId)
            .then((results) => {
              this.yonghuList =results.data

            });
        });

      // console.log(this.biaozhulist)
      // for(var i =0; i<this.biaozhulist.features.length;i++){
      //   debugger
      //   if(this.biaozhulist.features[i].properties==value){
      //     debugger
      //     let pointId ={
      //       pointId:this.biaozhulist[i].pointId
      //     }
      //
      // }


    },
     drawEntityByJson() {
        // 获取本地json
        $.ajax({
            type: "get",
            url:  "/chenglicun/r3dUtil/map/test1.json",
            async: false,
            success: function (results) {
                var strjson = results; //上图json
                var isClearForOpenFile = true; //是否清除已上图的entity
                var isFly = true; //上图后是否飞行到entity

                var plotWidget = reds3d.widget.getClass('/chenglicun/r3dUtil/map/widgets/plot-api/widget.js');
                if (plotWidget) {
                    plotWidget.jsonToLayer(strjson, isClearForOpenFile, isFly)
                }else{
                    haoutil.alert('标绘组件未打开');
                }
            }
        });
     },
     deletePlotEntity() {
        var plotWidget = reds3d.widget.getClass('/chenglicun/r3dUtil/map/widgets/plot-api/widget.js');
        if (plotWidget) {
            plotWidget.deleteAll();
        }
     },
     viewerEntityOnMap(){
        //添加图标点
        window.viewer.entities.add({
            id: "point_1",
            name: "测试点",
            position: Redslib.Cartesian3.fromDegrees(120.466753, 31.655606, 6),
            billboard: {
                image: '/chenglicun/r3dUtil/map/img/marker/mark1.png',
                horizontalOrigin: Redslib.HorizontalOrigin.CENTER,
                verticalOrigin: Redslib.VerticalOrigin.BOTTOM,
                scale: 0.5,
            },
            tooltip: { html: `<div style='min-width: 200px;text-align: center'>测试名称</div>` },
            popup: {
                html: `
                <div style = "width: 200px; height: 50px;">
                    <p>弹窗测试内容一</p>
                    <p>弹窗测试内容一二</p>
                </div>
                `,
                anchor: [0, -20]
            }
        });
     },
     deleteViewerEntity() {
        //debugger
       var entity = window.viewer.entities.getById("point_1");
        window.viewer.entities.remove(entity);
     }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #121414;
}
.test-btn{
    position: absolute;
    top: 0;
    left: 0;
    display: inline-grid;
}
.tips{
  position: absolute !important;
  top: 10%;

}
.tan{
  padding: 10px;
  position: absolute;
  top: 10%;
  left: 10%;
  width: 300px;
  height: 500px;
  color: #FFFFFF;
  background-color: rgba(30,36,50,0.6);
  border: 0;
  font-size: 16px;
}
.title_tan{
  width: 100%;
  height: 40px;
  font-size: 24px;
  line-height: 40px;
}
</style>
